@{
    ViewData["Title"] = "数据库管理";
}

<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h1>数据库管理系统</h1>
                <a href="/Home/Logout" class="btn btn-secondary">
                    <i class="bi bi-box-arrow-right"></i> 登出
                </a>
            </div>
            <ul class="nav nav-tabs" id="mainTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="accounts-tab" data-bs-toggle="tab" data-bs-target="#accounts" type="button" role="tab">账号管理</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="databases-tab" data-bs-toggle="tab" data-bs-target="#databases" type="button" role="tab">数据库管理</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="permissions-tab" data-bs-toggle="tab" data-bs-target="#permissions" type="button" role="tab">权限管理</button>
                </li>
            </ul>
            <div class="tab-content" id="mainTabsContent">
                <!-- 账号管理 -->
                <div class="tab-pane fade show active" id="accounts" role="tabpanel">
                    <div class="card mt-3">
                        <div class="card-header">
                            <h5>账号列表</h5>
                            <button class="btn btn-primary" onclick="showCreateAccountModal()">创建账号</button>
                        </div>
                        <div class="card-body">
                            <table class="table table-striped" id="accountsTable">
                                <thead>
                                    <tr>
                                        <th>登录名</th>
                                        <th>类型</th>
                                        <th>默认数据库</th>
                                        <th>状态</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- 数据将通过 AJAX 加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- 数据库管理 -->
                <div class="tab-pane fade" id="databases" role="tabpanel">
                    <div class="card mt-3">
                        <div class="card-header">
                            <h5>数据库列表</h5>
                            <button class="btn btn-primary" onclick="showCreateDatabaseModal()">创建数据库</button>
                        </div>
                        <div class="card-body">
                            <table class="table table-striped" id="databasesTable">
                                <thead>
                                    <tr>
                                        <th>数据库名称</th>
                                        <th>所有者</th>
                                        <th>状态</th>
                                        <th>恢复模式</th>
                                        <th>大小(MB)</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- 数据将通过 AJAX 加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- 权限管理 -->
                <div class="tab-pane fade" id="permissions" role="tabpanel">
                    <div class="card mt-3">
                        <div class="card-header">
                            <h5>权限管理</h5>
                        </div>
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label for="permissionAccountSelect" class="form-label">选择账号</label>
                                    <select class="form-select" id="permissionAccountSelect">
                                        <!-- 选项将通过 AJAX 加载 -->
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label for="permissionDatabaseSelect" class="form-label">选择数据库</label>
                                    <select class="form-select" id="permissionDatabaseSelect">
                                        <!-- 选项将通过 AJAX 加载 -->
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label for="permissionLevelSelect" class="form-label">权限级别</label>
                                    <select class="form-select" id="permissionLevelSelect">
                                        <option value="ReadOnly">只读</option>
                                        <option value="ReadWrite">读写</option>
                                        <option value="DDLAdmin">DDL管理员</option>
                                        <option value="Owner">所有者</option>
                                    </select>
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <button class="btn btn-success" onclick="grantPermission()">授予权限</button>
                                    <button class="btn btn-warning" onclick="revokePermission()">撤销权限</button>
                                    <button class="btn btn-info" onclick="checkPermission()">检查权限</button>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div id="permissionResult" class="alert" style="display: none;"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 创建账号模态框 -->
<div class="modal fade" id="createAccountModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">创建账号</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="createAccountForm">
                    <div class="mb-3">
                        <label for="loginName" class="form-label">登录名</label>
                        <input type="text" class="form-control" id="loginName" required>
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">密码</label>
                        <input type="password" class="form-control" id="password" required>
                    </div>
                    <div class="mb-3">
                        <label for="defaultDatabase" class="form-label">默认数据库</label>
                        <input type="text" class="form-control" id="defaultDatabase" value="master">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="createAccount()">创建</button>
            </div>
        </div>
    </div>
</div>

<!-- 创建数据库模态框 -->
<div class="modal fade" id="createDatabaseModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">创建数据库</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="createDatabaseForm">
                    <div class="mb-3">
                        <label for="databaseName" class="form-label">数据库名称</label>
                        <input type="text" class="form-control" id="databaseName" required>
                    </div>
                    <div class="mb-3">
                        <label for="collation" class="form-label">排序规则</label>
                        <input type="text" class="form-control" id="collation" value="Chinese_PRC_CI_AS">
                    </div>
                    <div class="mb-3">
                        <label for="recoveryModel" class="form-label">恢复模式</label>
                        <select class="form-select" id="recoveryModel">
                            <option value="SIMPLE">简单</option>
                            <option value="FULL">完整</option>
                            <option value="BULK_LOGGED">大容量日志</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="createDatabase()">创建</button>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        // 页面加载时获取数据
        $(document).ready(function() {
            loadAccounts();
            loadDatabases();
            loadAccountsForPermission();
            loadDatabasesForPermission();
        });

        // 加载账号列表
        function loadAccounts() {
            $.get('/api/DatabaseManagement/accounts', function(data) {
                if (data.success) {
                    var tbody = $('#accountsTable tbody');
                    tbody.empty();
                    $.each(data.data, function(index, account) {
                        var row = '<tr>' +
                            '<td>' + account.loginName + '</td>' +
                            '<td>' + account.accountType + '</td>' +
                            '<td>' + account.defaultDatabase + '</td>' +
                            '<td>' + account.status + '</td>' +
                            '<td>' + (account.createDate ? new Date(account.createDate).toLocaleString() : '') + '</td>' +
                            '<td>' +
                            '<button class="btn btn-sm btn-warning" onclick="toggleAccountStatus(\'' + account.loginName + '\', ' + !account.isDisabled + ')">' + 
                            (account.isDisabled ? '启用' : '禁用') + '</button> ' +
                            '<button class="btn btn-sm btn-danger" onclick="deleteAccount(\'' + account.loginName + '\')">删除</button>' +
                            '</td>' +
                            '</tr>';
                        tbody.append(row);
                    });
                } else {
                    alert('加载账号列表失败: ' + data.message);
                }
            }).fail(function() {
                alert('加载账号列表失败');
            });
        }

        // 加载数据库列表
        function loadDatabases() {
            $.get('/api/DatabaseManagement/databases', function(data) {
                if (data.success) {
                    var tbody = $('#databasesTable tbody');
                    tbody.empty();
                    $.each(data.data, function(index, database) {
                        var row = '<tr>' +
                            '<td>' + database.databaseName + '</td>' +
                            '<td>' + database.owner + '</td>' +
                            '<td>' + database.state + '</td>' +
                            '<td>' + database.recoveryModel + '</td>' +
                            '<td>' + database.sizeMB.toFixed(2) + '</td>' +
                            '<td>' + (database.createDate ? new Date(database.createDate).toLocaleString() : '') + '</td>' +
                            '<td>' +
                            '<button class="btn btn-sm btn-danger" onclick="deleteDatabase(\'' + database.databaseName + '\')">删除</button>' +
                            '</td>' +
                            '</tr>';
                        tbody.append(row);
                    });
                } else {
                    alert('加载数据库列表失败: ' + data.message);
                }
            }).fail(function() {
                alert('加载数据库列表失败');
            });
        }

        // 加载账号下拉列表（权限管理）
        function loadAccountsForPermission() {
            $.get('/api/DatabaseManagement/accounts', function(data) {
                if (data.success) {
                    var select = $('#permissionAccountSelect');
                    select.empty();
                    $.each(data.data, function(index, account) {
                        select.append('<option value="' + account.loginName + '">' + account.loginName + '</option>');
                    });
                }
            });
        }

        // 加载数据库下拉列表（权限管理）
        function loadDatabasesForPermission() {
            $.get('/api/DatabaseManagement/databases', function(data) {
                if (data.success) {
                    var select = $('#permissionDatabaseSelect');
                    select.empty();
                    $.each(data.data, function(index, database) {
                        select.append('<option value="' + database.databaseName + '">' + database.databaseName + '</option>');
                    });
                }
            });
        }

        // 显示创建账号模态框
        function showCreateAccountModal() {
            $('#createAccountForm')[0].reset();
            $('#createAccountModal').modal('show');
        }

        // 创建账号
        function createAccount() {
            var requestData = {
                loginName: $('#loginName').val(),
                password: $('#password').val(),
                defaultDatabase: $('#defaultDatabase').val()
            };

            $.ajax({
                url: '/api/DatabaseManagement/accounts',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(requestData),
                success: function(data) {
                    if (data.success) {
                        $('#createAccountModal').modal('hide');
                        loadAccounts();
                        loadAccountsForPermission();
                        alert('账号创建成功');
                    } else {
                        alert('账号创建失败: ' + data.message);
                    }
                },
                error: function() {
                    alert('账号创建失败');
                }
            });
        }

        // 显示创建数据库模态框
        function showCreateDatabaseModal() {
            $('#createDatabaseForm')[0].reset();
            $('#createDatabaseModal').modal('show');
        }

        // 创建数据库
        function createDatabase() {
            var requestData = {
                databaseName: $('#databaseName').val(),
                collation: $('#collation').val(),
                recoveryModel: $('#recoveryModel').val()
            };

            $.ajax({
                url: '/api/DatabaseManagement/databases',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(requestData),
                success: function(data) {
                    if (data.success) {
                        $('#createDatabaseModal').modal('hide');
                        loadDatabases();
                        loadDatabasesForPermission();
                        alert('数据库创建成功');
                    } else {
                        alert('数据库创建失败: ' + data.message);
                    }
                },
                error: function() {
                    alert('数据库创建失败');
                }
            });
        }

        // 删除账号
        function deleteAccount(loginName) {
            if (confirm('确定要删除账号 ' + loginName + ' 吗？')) {
                $.ajax({
                    url: '/api/DatabaseManagement/accounts/' + loginName,
                    type: 'DELETE',
                    success: function(data) {
                        if (data.success) {
                            loadAccounts();
                            loadAccountsForPermission();
                            alert('账号删除成功');
                        } else {
                            alert('账号删除失败: ' + data.message);
                        }
                    },
                    error: function() {
                        alert('账号删除失败');
                    }
                });
            }
        }

        // 启用/禁用账号
        function toggleAccountStatus(loginName, disable) {
            $.ajax({
                url: '/api/DatabaseManagement/accounts/' + loginName + '/status?disable=' + disable,
                type: 'PUT',
                success: function(data) {
                    if (data.success) {
                        loadAccounts();
                        alert(disable ? '账号已禁用' : '账号已启用');
                    } else {
                        alert('操作失败: ' + data.message);
                    }
                },
                error: function() {
                    alert('操作失败');
                }
            });
        }

        // 删除数据库
        function deleteDatabase(databaseName) {
            if (confirm('确定要删除数据库 ' + databaseName + ' 吗？')) {
                $.ajax({
                    url: '/api/DatabaseManagement/databases/' + databaseName,
                    type: 'DELETE',
                    success: function(data) {
                        if (data.success) {
                            loadDatabases();
                            loadDatabasesForPermission();
                            alert('数据库删除成功');
                        } else {
                            alert('数据库删除失败: ' + data.message);
                        }
                    },
                    error: function() {
                        alert('数据库删除失败');
                    }
                });
            }
        }

        // 授予权限
        function grantPermission() {
            var requestData = {
                loginName: $('#permissionAccountSelect').val(),
                databaseName: $('#permissionDatabaseSelect').val(),
                permissionLevel: $('#permissionLevelSelect').val()
            };

            $.ajax({
                url: '/api/DatabaseManagement/permissions/grant',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(requestData),
                success: function(data) {
                    if (data.success) {
                        showPermissionResult('权限授予成功', 'alert-success');
                    } else {
                        showPermissionResult('权限授予失败: ' + data.message, 'alert-danger');
                    }
                },
                error: function() {
                    showPermissionResult('权限授予失败', 'alert-danger');
                }
            });
        }

        // 撤销权限
        function revokePermission() {
            var requestData = {
                loginName: $('#permissionAccountSelect').val(),
                databaseName: $('#permissionDatabaseSelect').val()
            };

            $.ajax({
                url: '/api/DatabaseManagement/permissions/revoke',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(requestData),
                success: function(data) {
                    if (data.success) {
                        showPermissionResult('权限撤销成功', 'alert-success');
                    } else {
                        showPermissionResult('权限撤销失败: ' + data.message, 'alert-danger');
                    }
                },
                error: function() {
                    showPermissionResult('权限撤销失败', 'alert-danger');
                }
            });
        }

        // 检查权限
        function checkPermission() {
            var loginName = $('#permissionAccountSelect').val();
            var databaseName = $('#permissionDatabaseSelect').val();

            $.get('/api/DatabaseManagement/permissions/check?loginName=' + loginName + '&databaseName=' + databaseName, function(data) {
                if (data.success) {
                    showPermissionResult(
                        '账号 ' + loginName + ' ' + (data.data.hasPermission ? '有' : '无') + 
                        ' 访问数据库 ' + databaseName + ' 的权限', 
                        data.data.hasPermission ? 'alert-success' : 'alert-warning'
                    );
                } else {
                    showPermissionResult('检查权限失败: ' + data.message, 'alert-danger');
                }
            }).fail(function() {
                showPermissionResult('检查权限失败', 'alert-danger');
            });
        }

        // 显示权限操作结果
        function showPermissionResult(message, alertClass) {
            var resultDiv = $('#permissionResult');
            resultDiv.removeClass('alert-success alert-warning alert-danger');
            resultDiv.addClass(alertClass);
            resultDiv.text(message);
            resultDiv.show();
        }
    </script>
}